<script lang="ts">
    import dayjs from "dayjs";
    import type { CountDownProps } from "./CountDown";
    import { onDestroy, onMount } from "svelte";
    import { useClassList } from "../utils/useClassList";

    let timer: any;

    const props: CountDownProps = $props();
    let now = $state(new Date().getTime());

    function fixedZero(val: number) {
        return `${val}`.padStart(2, "0");
    }
    const text = () => {
        let val: any = props.value;
        if (typeof val === "string" || val instanceof Date) {
            val = dayjs(val).toDate().getTime();
        }
        let offset: number = val - now;
        if (offset <= 0) {
            if (timer) {
                clearInterval(timer);
                timer = null;
            }
            if (props.onend) {
                props.onend();
            }
            offset = 0;
        }
        const days = fixedZero(parseInt(offset / (1000 * 60 * 60 * 24) + "", 10));
        const hours = fixedZero(parseInt(offset / (1000 * 60 * 60) + "", 10) % 24);
        const minutes = fixedZero(parseInt(offset / (1000 * 60) + "", 10) % 60);
        const seconds = fixedZero(parseInt(offset / 1000 + "", 10) % 60);

        const format = props.format ?? "HH:mm:ss";
        let ret: string = format;
        if (format.match(/D+/)) {
            ret = ret.replace(/D+/, days + "");
        }
        if (format.match(/H+/)) {
            ret = ret.replace(/H+/, hours + "");
        }
        if (format.match(/m+/)) {
            ret = ret.replace(/m+/, minutes + "");
        }
        if (format.match(/s+/)) {
            ret = ret.replace(/s+/, seconds + "");
        }
        return ret;
    };

    const update = () => {
        timer = setInterval(() => {
            now = new Date().getTime();
        }, 1000);
    };
    onMount(() => {
        update();
    });

    onDestroy(() => {
        clearInterval(timer);
        timer = null;
    });

    const classList = $derived(useClassList(props, "cm-count-down"));
</script>

<span class={classList} style={props.style}>
    {#if props.prefix}
        <span class="cm-count-down-prefix">
            {#if typeof props.prefix === "function"}
                {@render props.prefix()}
            {:else}
                {props.prefix}
            {/if}
        </span>
    {/if}
    <span class="cm-count-down-value">{text()}</span>
    {#if props.suffix}
        <span class="cm-count-down-suffix">
            {#if typeof props.suffix === "function"}
                {@render props.suffix()}
            {:else}
                {props.suffix}
            {/if}
        </span>
    {/if}
</span>
